package com.example.guli.service.sms.controller.api;

import com.aliyuncs.exceptions.ClientException;
import com.example.guli.common.base.result.R;
import com.example.guli.common.base.util.sms.FormUtils;
import com.example.guli.common.base.util.sms.RandomUtils;
import com.example.guli.service.sms.service.SmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/sms")
@Api(description = "短信管理")
@CrossOrigin //跨域
@Slf4j
public class ApiSmsController {
    @Autowired
    private SmsService smsService;

    @ApiOperation("获取验证码")
    @GetMapping("send/{mobile}")
    public R getCode(
            @ApiParam(value = "根据手机号获取验证码",required = true)
            @PathVariable String mobile

    ) throws ClientException {
        /**
         * 手机号校验
         * 生成验证码
         * 发送验证码
         * 存储验证码
         */
        if(StringUtils.isEmpty(mobile)||!FormUtils.isMobile(mobile)){
            log.error("请输入合法的手机号！");
//            throw new GuliException(ResultCodeEnum.LOGIN_PHONE_ERROR);
            return R.error().message("请输入合法的手机号！").code(28001);
        }
        //生成随机数，以随机数作为验证码，将随机数传递给阿里云短信
        String checkCode = RandomUtils.getFourBitRandom();
        smsService.send(mobile,checkCode);
        return R.ok().data("data",checkCode).message("短信发送成功");


    }

}
